package com.tms.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tms.basic.mapper.DriverMapper;
import com.tms.basic.pojo.domain.Driver;
import com.tms.basic.pojo.req.DriverQueryReq;
import com.tms.basic.pojo.vo.DriverVO;
import com.tms.basic.service.DriverService;
import com.tms.common.core.common.Constant;
import com.tms.common.core.domain.R;
import com.tms.common.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 驾驶员信息服务实现类
 *
 * @author TMS
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements DriverService {

    private final DriverMapper driverMapper;

    @Override
    public R<IPage<DriverVO>> getDriverPage(DriverQueryReq req) {
        try {
            Page<DriverVO> page = new Page<>(req.getCurrent(), req.getSize());
            IPage<DriverVO> result = driverMapper.selectDriverPage(page, req);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾驶员信息失败：" + e.getMessage());
        }
    }

    @Override
    public R<List<DriverVO>> getDriverList(DriverQueryReq req) {
        try {
            List<DriverVO> result = driverMapper.selectDriverList(req);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾驶员列表失败：" + e.getMessage());
        }
    }

    @Override
    public R<DriverVO> getDriverById(Long id) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员ID"));
        }
        
        try {
            DriverVO result = driverMapper.selectDriverById(id);
            if (result == null) {
                return R.failed(String.format(Constant.ErrorMessage.RECORD_NOT_FOUND, id));
            }
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾驶员详情失败：" + e.getMessage());
        }
    }

    @Override
    public R<DriverVO> getDriverByPhoneNumber(String phoneNumber) {
        if (!StringUtils.hasText(phoneNumber)) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "手机号"));
        }
        
        try {
            DriverVO result = driverMapper.selectDriverByPhoneNumber(phoneNumber);
            if (result == null) {
                return R.failed("未找到手机号为 " + phoneNumber + " 的驾驶员");
            }
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾驶员信息失败：" + e.getMessage());
        }
    }

    @Override
    public R<DriverVO> getDriverByIdCardNumber(String idCardNumber) {
        if (!StringUtils.hasText(idCardNumber)) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "身份证号"));
        }
        
        try {
            DriverVO result = driverMapper.selectDriverByIdCardNumber(idCardNumber);
            if (result == null) {
                return R.failed("未找到身份证号为 " + idCardNumber + " 的驾驶员");
            }
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾驶员信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> addDriver(Driver driver) {
        if (driver == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员信息"));
        }
        
        try {
            // 检查手机号是否已存在
            if (isPhoneNumberExists(driver.getPhoneNumber(), null)) {
                return R.failed(String.format(Constant.ErrorMessage.PHONE_NUMBER_EXISTS, driver.getPhoneNumber()));
            }
            
            // 检查身份证号是否已存在
            if (StringUtils.hasText(driver.getIdCardNumber()) && 
                isIdCardNumberExists(driver.getIdCardNumber(), null)) {
                return R.failed(String.format(Constant.ErrorMessage.ID_CARD_EXISTS, driver.getIdCardNumber()));
            }
            
            boolean result = this.save(driver);
            return result ? R.success(true, "驾驶员添加成功") : R.failed("驾驶员添加失败");
        } catch (Exception e) {
            throw new BusinessException("驾驶员添加失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> updateDriver(Driver driver) {
        if (driver == null || driver.getId() == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员信息或驾驶员ID"));
        }
        
        try {
            // 检查手机号是否已存在（排除自己）
            if (isPhoneNumberExists(driver.getPhoneNumber(), driver.getId())) {
                return R.failed(String.format(Constant.ErrorMessage.PHONE_NUMBER_EXISTS, driver.getPhoneNumber()));
            }
            
            // 检查身份证号是否已存在（排除自己）
            if (StringUtils.hasText(driver.getIdCardNumber()) && 
                isIdCardNumberExists(driver.getIdCardNumber(), driver.getId())) {
                return R.failed(String.format(Constant.ErrorMessage.ID_CARD_EXISTS, driver.getIdCardNumber()));
            }
            
            boolean result = this.updateById(driver);
            return result ? R.success(true, "驾驶员修改成功") : R.failed("驾驶员修改失败");
        } catch (Exception e) {
            throw new BusinessException("驾驶员修改失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> deleteDriver(Long id) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员ID"));
        }
        
        try {
            boolean result = this.removeById(id);
            return result ? R.success(true, "驾驶员删除成功") : R.failed("驾驶员删除失败");
        } catch (Exception e) {
            throw new BusinessException("驾驶员删除失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> deleteDriverBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员ID列表"));
        }
        
        try {
            boolean result = this.removeByIds(ids);
            return result ? R.success(true, "批量删除驾驶员成功") : R.failed("批量删除驾驶员失败");
        } catch (Exception e) {
            throw new BusinessException("批量删除驾驶员失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> updateDriverStatus(Long id, Integer status) {
        if (id == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员ID"));
        }
        if (status == null) {
            return R.validateFailed(String.format(Constant.ErrorMessage.PARAM_NOT_NULL, "驾驶员状态"));
        }
        
        // 验证状态值的有效性
        if (status < Constant.DriverStatus.IDLE || status > Constant.DriverStatus.RESIGNED) {
            return R.validateFailed(String.format(Constant.ErrorMessage.INVALID_STATUS, status));
        }
        
        try {
            Driver driver = new Driver();
            driver.setId(id);
            driver.setDriverStatus(status);
            boolean result = this.updateById(driver);
            return result ? R.success(true, "驾驶员状态更新成功") : R.failed("驾驶员状态更新失败");
        } catch (Exception e) {
            throw new BusinessException("驾驶员状态更新失败：" + e.getMessage(), e);
        }
    }

    @Override
    public R<List<DriverVO>> getLicenseExpiringDrivers(Integer days) {
        try {
            if (days == null || days <= 0) {
                days = Constant.DefaultValue.DEFAULT_REMIND_DAYS;
            }
            List<DriverVO> result = driverMapper.selectLicenseExpiringDrivers(days);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询驾照即将到期驾驶员失败：" + e.getMessage());
        }
    }

    @Override
    public R<List<Map<String, Object>>> countDriverByStatus(Long organizationId) {
        try {
            List<Map<String, Object>> result = driverMapper.countDriverByStatus(organizationId);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("统计驾驶员状态失败：" + e.getMessage());
        }
    }

    @Override
    public R<List<DriverVO>> getAvailableDrivers(String licenseType, Long organizationId) {
        try {
            List<DriverVO> result = driverMapper.selectAvailableDrivers(licenseType, organizationId);
            return R.success(result);
        } catch (Exception e) {
            return R.failed("查询空闲驾驶员失败：" + e.getMessage());
        }
    }

    @Override
    public boolean isPhoneNumberExists(String phoneNumber, Long excludeId) {
        if (!StringUtils.hasText(phoneNumber)) {
            return false;
        }
        
        LambdaQueryWrapper<Driver> queryWrapper = new LambdaQueryWrapper<Driver>()
                .eq(Driver::getPhoneNumber, phoneNumber);
        
        if (excludeId != null) {
            queryWrapper.ne(Driver::getId, excludeId);
        }
        
        return this.count(queryWrapper) > 0;
    }

    @Override
    public boolean isIdCardNumberExists(String idCardNumber, Long excludeId) {
        if (!StringUtils.hasText(idCardNumber)) {
            return false;
        }
        
        LambdaQueryWrapper<Driver> queryWrapper = new LambdaQueryWrapper<Driver>()
                .eq(Driver::getIdCardNumber, idCardNumber);
        
        if (excludeId != null) {
            queryWrapper.ne(Driver::getId, excludeId);
        }
        
        return this.count(queryWrapper) > 0;
    }
} 